<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="客户名称">
              <!-- <input type="text" v-model="keyWorld">
	            <h3>{{keyWorld}}</h3> -->
              <a-input v-model:value="where.name" placeholder="请输入" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="审核">
              <a-select v-model:value="where.state" placeholder="请选择" allow-clear>
                <a-select-option value="">所有</a-select-option>
                <a-select-option value="未审核">未审核</a-select-option>
                <!-- <a-select-option value="未通过">未通过</a-select-option> -->
                <a-select-option value="已审核">已审核</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="客户类型">
              <a-select v-model:value="where.type" placeholder="请选择" allow-clear>
                <a-select-option value="">所有</a-select-option>
                <a-select-option value="货代">货代</a-select-option>
                <a-select-option value="外贸">外贸</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{ span: 24 }">
              <em></em>
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <!-- 
          @update:selection 单选/多选 选择改变事件
          v-model:current 显示表格 单选框
          :customRow  表格选择行
       -->
      <ele-pro-table ref="tableRef" row-key="id" :datasource="datasource" :columns="columns" :height="400"
        v-model:current="current" @update:selection="customerTableOnSelectionChange" :customRow="customerTableRowClick"
        :scroll="{ x: 2200 }">
        <template #toolbar>
          <a-space>
            <a-button v-any-permission="['order:customer:save']" type="primary" @click="openEdit()">
              <template #icon>
                <plus-outlined />
              </template>
              <span>新建</span>
            </a-button>
            <a-button v-if="current.id > 0" type="primary" @click="exportCustomer()">
              <template #icon>
                <plus-outlined />
              </template>
              <span>拖车账单</span>
            </a-button>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'invoiceState'">
            {{ record.invoiceState == 0 ? '不开票' : '开票' }}
          </template>
          <template v-else-if="column.key === 'message'">
            {{ record.message == 0 ? '不发送' : '发送' }}
          </template>
          <template v-else-if="column.key === 'gzhSend'">
            {{ record.gzhSend == 0 ? '不发送' : '发送' }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-popconfirm v-if="record.state != '已审核'" title="确定要审核此项吗？" @confirm="openExam(record)">
                <a class="ele-text-primary" v-any-permission="['order:customer:exam']">审核</a>
              </a-popconfirm>
              <a @click="openEdit(record)" v-any-permission="['order:customer:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="remove(record)">
                <a class="ele-text-danger" v-any-permission="['order:customer:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
      <ele-pro-table ref="cFactoryTableRef" row-key="id" :columns="cFactoryColumns" :datasource="cFactoryDatasource"
        :scroll="{ x: 1000 }">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="openCFactoryEdit()" v-any-permission="['order:customerFactory:save']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>新建</span>
            </a-button>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="openCFactoryEdit(record)" v-any-permission="['order:customerFactory:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="cFactoryRemove(record)">
                <a class="ele-text-danger" v-any-permission="['order:customerFactory:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
    <!-- 客户管理添加、修改弹窗 -->
    <ele-modal :width="900" v-model:visible="visible" :confirm-loading="loading" :title="isUpdate ? '修改客户管理' : '新建客户管理'"
      :body-style="{ paddingBottom: '8px' }" @ok="save" :maskClosable="false" :move-out="true" :resizable="false"
      :maxable="true" :reset-on-close="false" :inner="false">
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ md: { span: 7 }, sm: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-form-item label="账号" name="account">
          <a-input allow-clear :maxlength="50" placeholder="请输入客户账号" v-model:value="form.account" autocomplete="off"
            :disabled="isUpdate" />
        </a-form-item>
        <a-form-item label="客户类型" name="type">
          <a-select v-model:value="form.type" placeholder="请选择">
            <a-select-option value="货代">货代</a-select-option>
            <a-select-option value="外贸">外贸</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="客户名称" name="name">
          <a-input allow-clear :maxlength="50" placeholder="请输入客户名称" v-model:value="form.name" autocomplete="off" />
        </a-form-item>
        <a-form-item label="客户简称" name="abbreviation">
          <a-input allow-clear :maxlength="50" placeholder="请输入客户简称" v-model:value="form.abbreviation"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="email" name="email">
          <a-input allow-clear :maxlength="50" placeholder="请输入email" v-model:value="form.email" autocomplete="off" />
        </a-form-item>
        <a-form-item label="联系人" name="contacts">
          <a-input allow-clear :maxlength="50" placeholder="请输入联系人" v-model:value="form.contacts" autocomplete="off" />
        </a-form-item>
        <a-form-item label="联系人电话" name="contactsPhone">
          <a-input allow-clear :maxlength="50" placeholder="请输入联系人电话" v-model:value="form.contactsPhone"
            autocomplete="off" />
        </a-form-item>
        <!-- <a-form-item label="道路运输许可证" name="roadTransportPermit">
          <a-upload v-model:file-list="roadTransportPermitFilelist" :customRequest="roadTransportPermitUploadFiles"
            list-type="picture-card" @preview="handlePreview" @remove="roadTransportPermitUploadFilesRemove">
            <div v-if="roadTransportPermitFilelist.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">Upload</div>
            </div>
          </a-upload>
        </a-form-item> -->
        <!-- <a-form-item label="合同" name="agreement">
          <a-input allow-clear :maxlength="50" placeholder="请输入合同" v-model:value="form.agreement" />
        </a-form-item> -->
        <a-form-item label="合同开始时间" name="agreementStart">
          <a-date-picker v-model:value="form.agreementStart" valueFormat="YYYY-MM-DD" placeholder="请输入合同开始时间"
            class="ele-fluid" />
        </a-form-item>
        <a-form-item label="合同结束时间" name="agreementEnd">
          <a-date-picker v-model:value="form.agreementEnd" valueFormat="YYYY-MM-DD" placeholder="请输入合同结束时间"
            class="ele-fluid" />
        </a-form-item>
        <a-input allow-clear style="display: none;" :maxlength="50" placeholder="请输入业务员Id"
          v-model:value="form.salesmanid" />
        <a-input allow-clear style="display: none;" :maxlength="50" placeholder="请输入业务员" v-model:value="form.salesman" />
        <a-form-item label="业务员" name="salesman">
          <a-select v-model:value="salesman_value" show-search label-in-value placeholder="请选择业务员" allow-clear
            :options="company_options" :filter-option="salesman_filterOption" @change="salesman_handleChange"></a-select>
        </a-form-item>
        <a-input allow-clear style="display: none;" :maxlength="50" placeholder="请输入操作Id"
          v-model:value="form.operaterid" />
        <a-input allow-clear style="display: none;" :maxlength="50" placeholder="请输入操作" v-model:value="form.operater" />
        <a-form-item label="操作" name="operater">
          <a-select v-model:value="operater_value" show-search label-in-value placeholder="请选择操作" allow-clear
            :options="company_options" :filter-option="operater_filterOption" @change="operater_handleChange"></a-select>
        </a-form-item>
        <a-form-item label="结算周期" name="settle">
          <a-select v-model:value="form.settle" placeholder="请选择" allow-clear>
            <a-select-option value="周结">周结</a-select-option>
            <a-select-option value="十日结">十日结</a-select-option>
            <a-select-option value="半月结">半月结</a-select-option>
            <a-select-option value="月结">月结</a-select-option>
            <a-select-option value="二月结">二月结</a-select-option>
            <a-select-option value="三月结">三月结</a-select-option>
            <a-select-option value="年结">年结</a-select-option>
            <a-select-option value="签收付款">签收付款</a-select-option>
            <a-select-option value="提取付款">提取付款</a-select-option>
            <a-select-option value="到港付款">到港付款</a-select-option>
            <a-select-option value="货到付款">货到付款</a-select-option>
            <a-select-option value="见转单付款">见转单付款</a-select-option>
            <a-select-option value="现结">现结</a-select-option>
            <a-select-option value="预付">预付</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否开票" name="invoiceState">
          <a-select v-model:value="form.invoiceState" placeholder="请选择">
            <a-select-option value="0">不开票</a-select-option>
            <a-select-option value="1">开票</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否发送短信" name="message">
          <a-select v-model:value="form.message" placeholder="请选择">
            <a-select-option value="0">不发送</a-select-option>
            <a-select-option value="1">发送</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否发送公众号" name="gzhSend">
          <a-select v-model:value="form.gzhSend" placeholder="请选择">
            <a-select-option value="0">不发送</a-select-option>
            <a-select-option value="1">发送</a-select-option>
          </a-select>
        </a-form-item>
        <a-divider orientation="left">开票信息</a-divider>
        <a-form-item label="统一社会信用代码" name="socialCode">
          <a-input allow-clear :maxlength="50" placeholder="请输入统一社会信用代码" v-model:value="form.socialCode"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="开户行" name="bank">
          <a-input allow-clear :maxlength="50" placeholder="请输入开户行" v-model:value="form.bank" autocomplete="off" />
        </a-form-item>
        <a-form-item label="开户行账号" name="bankAccount">
          <a-input allow-clear :maxlength="50" placeholder="请输入开户行账号" v-model:value="form.bankAccount" autocomplete="off" />
        </a-form-item>
        <a-form-item label="公司地址" name="address">
          <a-input allow-clear :maxlength="50" placeholder="请输入公司地址" v-model:value="form.address" autocomplete="off" />
        </a-form-item>
        <a-form-item label="公司电话" name="bankTel">
          <a-input allow-clear :maxlength="50" placeholder="请输入公司电话" v-model:value="form.bankTel" autocomplete="off" />
        </a-form-item>
        <a-form-item label="营业执照图片" name="businessLicense">
          <!-- <a-upload v-model:file-list="businessLicenseFilelist" 
            :action="lin_token.base_url + '/file/upload'"
            :headers="lin_token.token_headers"
            list-type="picture-card" @preview="handlePreview">
            <div v-if="businessLicenseFilelist.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">Upload</div> -->
          <a-upload v-model:file-list="businessLicenseFilelist" :customRequest="businessLicenseUploadFiles"
            list-type="picture-card" @preview="handlePreview" @remove="businessLicenseUploadFilesRemove">
            <div v-if="businessLicenseFilelist.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </ele-modal>
    <!-- 工厂地址添加、修改弹窗 -->
    <ele-modal :width="460" v-model:visible="cFactoryVisible" :confirm-loading="cFactoryLoading"
      :title="cFactoryIsUpdate ? '修改工厂地址' : '新建工厂地址'" :body-style="{ paddingBottom: '8px' }" @ok="cFactorySave"
      :maskClosable="false">
      <a-form ref="cFactoryFormRef" :model="cFactoryForm" :rules="rules"
        :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-form-item label="地址" name="faddress">
          <a-input allow-clear :maxlength="200" placeholder="请输入地址" v-model:value="cFactoryForm.faddress"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="默认地址" name="fstate">
          <a-checkbox v-model:checked="cFactoryForm.fstate2"></a-checkbox>
        </a-form-item>
        <a-form-item label="经纬度" name="longitude">
          {{ cFactoryForm.longitude }}, {{ cFactoryForm.latitude }}
        </a-form-item>
        <a-form-item label="半径(米)" name="radius">
          <a-input allow-clear :maxlength="200" placeholder="请输入半径(米)" v-model:value="cFactoryForm.radius"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="备注" name="fremark">
          <a-input allow-clear :maxlength="200" placeholder="请输入备注" v-model:value="cFactoryForm.fremark"
            autocomplete="off" />
        </a-form-item>
      </a-form>
    </ele-modal>
    <!-- 客户费用导出弹窗 -->
    <ele-modal :width="460" v-model:visible="customerExportVisible" :confirm-loading="cFactoryLoading" :title="'客户费用导出'"
      position="center" :body-style="{ paddingBottom: '8px' }" @ok="customerExportSave" :maskClosable="false">
      <a-form :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-form-item label="客户" name="">
          {{ current.name }}
        </a-form-item>
        <a-form-item label="日期" name="factoryPackDate2">
          <a-range-picker v-model:value="factoryPackDate2" :format="YYYY - MM - DD" placeholder="" class="ele-fluid"
            :allow-clear="false" />
        </a-form-item>
      </a-form>
    </ele-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue';
import { toDateString } from 'ele-admin-pro';
import dayjs from 'dayjs';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import lin_token from '@/lin/utils/token-util-lin';
import keyWordsRef from '@/lin/utils/customref';

import { selectListSel } from '@/api/user/user';
import {
  pageCustomers, removeCustomer,
  addCustomer, updateCustomer,
  examCustomer, exportsCustomerContainerBill
  , exportsCustomerNtContainerBill
} from '@/api/order/customer';
import { pageCustomerFactorys, removeCustomerFactory, addCustomerFactory, updateCustomerFactory } from '@/api/order/customerFactory';
import { fileUpload } from '@/api/file';

import { API_BASE_URL, TOKEN_HEADER_NAME } from '@/config/setting';
import { getToken } from '@/utils/token-util';
import { TIME_OUT } from '@/config/damon';
import { useRoute } from 'vue-router';

const route = useRoute()
// const qType = ref(route.query.type)

// 表格实例
const tableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
  },
  {
    title: '客户名称',
    dataIndex: 'name',
    // sorter: true,
    fixed: 'left',
  },
  {
    title: '缩写',
    dataIndex: 'abbreviation',
    // sorter: true,
  },
  {
    title: '结算周期',
    dataIndex: 'settle',
    // sorter: true,
  },
  {
    title: '联系人',
    dataIndex: 'contacts',
    // sorter: true,
  },
  {
    title: '联系人电话',
    dataIndex: 'contactsPhone',
    // sorter: true,
  },
  {
    title: '公司地址',
    dataIndex: 'address',
    // sorter: true,
  },
  {
    title: '是否开票',
    dataIndex: 'invoiceState',
    key: 'invoiceState',
    // sorter: true,
  },
  {
    title: '业务员',
    dataIndex: 'salesman',
    // sorter: true,
  },
  {
    title: '操作员',
    dataIndex: 'operater',
    // sorter: true,
  },
  {
    title: '客户类型',
    dataIndex: 'type',
    // sorter: true,
  },
  {
    title: '状态',
    dataIndex: 'state',
    key: 'state',
    // sorter: true,
  },
  // {
  //   title: '发送短信',
  //   dataIndex: 'message',
  //   key: 'message',
  //   // sorter: true,
  // },
  // {
  //   title: '发送公众号',
  //   dataIndex: 'gzhSend',
  //   key: 'gzhSend',
  //   // sorter: true,
  // },
  {
    title: '账号',
    dataIndex: 'account',
    key: 'account',
    // sorter: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    // sorter: true,
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    // sorter: true,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    // sorter: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    // sorter: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: where, resetFields } = useFormData({
  username: '',
  sex: undefined,
  agreementStart: ref('2015/01/01'),
  agreementEnd: ref('2015/01/01'),
});
const handleResizeColumn = (w, col) => {
  col.width = w;
}



// 表格数据源
const datasource = ({ page, limit, where, orders }) => {
  where.type = '货代外贸'
  pageCustomers({ ...where, type: '货代外贸', ...orders, page, limit }).then((msg) => {
    console.log(msg);
  })
  return pageCustomers({ ...where, type: '货代外贸', ...orders, page, limit });
};

/* 搜索 */
const reload = () => {
  tableRef?.value?.reload({ page: 1, where: where });
};
const reload2 = () => {
  tableRef?.value?.reload();
};
let where_timeout = 0
watch(() => where, (val) => {
  clearTimeout(where_timeout)
  where_timeout = setTimeout(() => {
    reload()
  }, TIME_OUT);
},
  { deep: true }
)
/*  重置 */
const reset = () => {
  resetFields();
  reload();
};

/* 删除单个 */
const remove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeCustomer(record.id).then((msg) => {
    hide();
    message.success(msg);
    reload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const current = ref({ id: 0 });

// 弹窗是否打开
const visible = ref(false);

// 是否是修改
const isUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const formRef = ref(null);

//防止重复刷新
let tableFeresh = ref(true)
let tableFereshId = ref(0)

// 表单数据
const { form, resetFields: resetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
  businessLicense: '',
  roadTransportPermit: '',
  salesmanid: '',
  salesman: '',
});

//excel导出
function exportCustomer() {
  customerExportVisible.value = true
}
let factoryPackDate2 = ref([
  dayjs().startOf('month'),
  dayjs().endOf('month'),
  // dayjs().add(2, 'month'),
])

function getDate_self(op) {
  let monght_s = op.getMonth() + 1
  let day_s = op.getDate()
  if (monght_s < 10) { monght_s = '0' + monght_s }
  if (day_s < 10) { day_s = '0' + day_s }
  return op.getFullYear() + '-' + monght_s + '-' + day_s
}
/* 客户费用导出 */
const customerExportSave = () => {
  if (factoryPackDate2.value == null) {
    factoryPackDate2.value = []
  }
  if (factoryPackDate2.value.length > 0) {
    let date1 = getDate_self(new Date(factoryPackDate2.value[0]))
    let date2 = getDate_self(new Date(factoryPackDate2.value[1]))
    let dataStr = '?date1=' + date1 + '&date2=' + date2
      + '&customer=' + current.value.name + '&customerAbbreviation=' + current.value.abbreviation
      + '&type=应收'
    let url = API_BASE_URL + '/order/customer/exportsCustomerContainerBill' + dataStr
    // window.open(API_BASE_URL + '/order/customer/exportsCustomerContainerBill' + dataStr, '_blank');
    // window.location.href = API_BASE_URL + '/order/customer/exportsCustomerContainerBill' + dataStr;
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true); // get、post都可
    xhr.responseType = "blob";  // 转换流
    xhr.setRequestHeader(TOKEN_HEADER_NAME, getToken()); // token键值对
    xhr.onload = function () {
      if (this.status == 200) {
        var blob = this.response;
        var a = document.createElement("a")
        var url = window.URL.createObjectURL(blob)
        a.href = url
        a.download = current.value.name + " 账期：" + date1 + "到" + date2 + ".xlsx"  // 文件名
      }
      a.click()
      window.URL.revokeObjectURL(url)
    }
    xhr.send();
    message.success('导出成功');
    customerExportVisible.value = false
  } else {
  }
};

let customerTableRowClick = (record, index) => {
  return {
    onClick: (event) => {
      current.value = record;
      cFactoryWhere.customerId = current.value.id
      cFactoryReload()
    },
  }
}
let customerTableOnSelectionChange = (current_options) => {
  current.value = current_options[0];
  cFactoryWhere.customerId = current.value.id
  cFactoryReload()
};
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: record => ({
    disabled: record.name === 'Disabled User',
    // Column configuration not to be checked
    name: record.name,
  }),
};
// let rowSelection = {
//   onChange: (selectedRowKeys, selectedRows) => {
//     // state.selectedRowKeys = selectedRowKeys;
//     console.log(
//       `selectedRowKeys: ${selectedRowKeys}`,
//       "selectedRows: ${selectedRows}",
//     );
//   },
//   type: 'radio'
// }
let businessLicenseFilelist = ref([]);
let roadTransportPermitFilelist = ref([]);
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

let businessLicenseUploadFiles = (info) => {
  //开始真正上传
  //上传接口
  //调用公共上传方法
  fileUpload({ 'file': info.file, 'path2': 'chf_customer' }).then((msg) => {
    const upload_file_list_tmp_arr = {}
    upload_file_list_tmp_arr['uid'] = info.file.uid
    upload_file_list_tmp_arr['name'] = info.file.name
    upload_file_list_tmp_arr['status'] = 'done'
    upload_file_list_tmp_arr['url'] = msg.data.path + "?path2=chf_customer"

    let arr = form.businessLicense == '' ? [] : JSON.parse(form.businessLicense)
    arr.push(upload_file_list_tmp_arr)
    form.businessLicense = JSON.stringify(arr)

    businessLicenseFilelist.value == undefined || businessLicenseFilelist.value.map(element => {
      element.status = 'done'
      // element.url = API_BASE_URL + '/file/' + element.url
    })
    message.success('上传成功');
  }).catch((e) => {
    message.error(e.message);
  });
}
let businessLicenseUploadFilesRemove = info => {
  let arr = JSON.parse(form.businessLicense)
  arr.splice(arr.findIndex(item => item.uid == info.uid), 1)
  form.businessLicense = JSON.stringify(arr)
}

let roadTransportPermitUploadFiles = (info) => {
  //开始真正上传
  //上传接口
  //调用公共上传方法
  fileUpload({ 'file': info.file, 'path2': 'chf_customer' }).then((msg) => {
    const upload_file_list_tmp_arr = {}
    upload_file_list_tmp_arr['uid'] = info.file.uid
    upload_file_list_tmp_arr['name'] = info.file.name
    upload_file_list_tmp_arr['status'] = 'done'
    upload_file_list_tmp_arr['url'] = msg.data.path + "?path2=chf_customer"
    let arr = form.roadTransportPermit == '' ? [] : JSON.parse(form.roadTransportPermit)
    arr.push(upload_file_list_tmp_arr)
    form.roadTransportPermit = JSON.stringify(arr)

    roadTransportPermitFilelist.value == undefined || roadTransportPermitFilelist.value.map(element => {
      element.status = 'done'
      // element.url = API_BASE_URL + '/file/' + element.url
    })
    message.success('上传成功');

  }).catch((e) => {
    message.error(e.message);
  });
}
let roadTransportPermitUploadFilesRemove = info => {
  let arr = JSON.parse(form.roadTransportPermit)
  arr.splice(arr.findIndex(item => item.uid == info.uid), 1)
  form.roadTransportPermit = JSON.stringify(arr)
}

const fileUploadOpenForm = (record) => {
  businessLicenseFilelist.value = []
  roadTransportPermitFilelist.value = []
  if (record != undefined) {
    if (record.businessLicense != '') {
      let t_list = JSON.parse(record.businessLicense)
      t_list.map(element => { element.url = API_BASE_URL + '/file/' + element.url })
      businessLicenseFilelist.value = [...t_list]
    }
    if (record.roadTransportPermit != '') {
      let t_list = JSON.parse(record.roadTransportPermit)
      t_list.map(element => { element.url = API_BASE_URL + '/file/' + element.url })
      roadTransportPermitFilelist.value = [...t_list]
    }
  }
}

let company_options = ref([]);
const salesman_value = ref({ value: '', label: '' });
const operater_value = ref({ value: '', label: '' });
selectListSel({ 'type': '平台用户' }).then((msg) => {
  company_options.value = msg
}).catch((e) => {
  message.error(e.message);
});
const salesman_handleChange = info => {
  form.salesmanid = ''
  form.salesman = ''
  if (info != undefined) {
    form.salesmanid = info.key + ''
    form.salesman = info.label
  }
};
const salesman_filterOption = (input, option) => {
  return option.label.indexOf(input) >= 0;
};

const operater_handleChange = info => {
  form.operaterid = info.key + ''
  form.operater = info.label
};
const operater_filterOption = (input, option) => {
  return option.label.indexOf(input) >= 0;
};


// 表单验证规则
const rules = reactive({
  account: [
    { required: true, message: '请输入账号', type: 'string', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入客户名称', type: 'string', trigger: 'blur' }
  ],
  abbreviation: [
    { required: true, message: '请输入客户简称', type: 'string', trigger: 'blur' }
  ],
  contacts: [
    { required: true, message: '请输入联系人', type: 'string', trigger: 'blur' }
  ],
  contactsPhone: [
    { required: true, message: '请输入联系人电话', type: 'string', trigger: 'blur' }
  ],
  salesman: [
    { required: true, message: '请选择业务员', type: 'string', trigger: 'blur' }
  ],
  operater: [
    { required: true, message: '请选择操作员', type: 'string', trigger: 'blur' }
  ],
});

const openExam = (record) => {
  examCustomer({ id: record.id, state: '已审核' }).then((msg) => {
    reload2()
    message.success(msg);
  }).catch((e) => {
    message.error(e.message);
  });
}
/* 打开编辑弹窗 */
const openEdit = (record) => {
  resetFormFields();
  formRef.value?.clearValidate();
  current.value = record ?? {};
  visible.value = true;
  Object.assign(form, record ?? {});
  fileUploadOpenForm(record)
  salesman_value.value = { value: form.salesmanid, label: form.salesman }
  operater_value.value = { value: form.operaterid, label: form.operater }
  if (record == undefined) {
    form.settle = '月结'
    form.invoiceState = '1'
    form.message = '0'
    form.gzhSend = '0'
    form.state = '未审核'
    form.type = '货代'
  } else {
    form.invoiceState += ''
    form.message += ''
    form.gzhSend += ''
  }
  isUpdate.value = !!record;
};

/* 保存编辑 */
const save = () => {
  if (!formRef.value) {
    return;
  }
  console.log(777);
  formRef.value.validate().then(() => {
  console.log(444);
    loading.value = true;
    const saveOrUpdate = isUpdate.value ? updateCustomer : addCustomer;
    saveOrUpdate(form).then((msg) => {
  console.log(5555);
      loading.value = false;
      message.success(msg);
      visible.value = false;
      reload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};

// let keyWorld=keyWordsRef("111")
//-----------------工厂地址customer factory-----------------------

const cFactoryTableRef = ref(null);

const cFactoryColumns = [
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (cFactoryTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '地址',
    dataIndex: 'faddress',
    key: 'faddress',
    // sorter: true,
  },
  {
    title: '默认地址',
    dataIndex: 'fstate',
    key: 'fstate',
    // sorter: true,
  },
  {
    title: '经度',
    dataIndex: 'longitude',
    key: 'longitude',
    // sorter: true,
  },
  {
    title: '纬度',
    dataIndex: 'latitude',
    key: 'latitude',
    // sorter: true,
  },
  {
    title: '半径',
    dataIndex: 'radius',
    key: 'radius',
    // sorter: true,
  },
  {
    title: '备注',
    dataIndex: 'fremark',
    key: 'fremark',
    // sorter: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    hideInSetting: true
  }];

// 表单数据
const { form: cFactoryWhere, resetFields: cFactoryResetFields } = useFormData({
  username: '',
  sex: undefined,
  customerId: 0
});

// 表格数据源
const cFactoryDatasource = ({ page, limit, where, orders }) => {
  return pageCustomerFactorys({ ...where, ...orders, page, limit });
};

let timeout = 0
/* 搜索 */
const cFactoryReload = () => {
  clearTimeout(timeout)
  timeout = setTimeout(() => { tableFeresh.value = true }, 2000);
  if (tableFereshId.value == current.value.id && !tableFeresh.value) {
    return
  }
  tableFeresh.value = false
  tableFereshId.value = current.value.id
  cFactoryTableRef?.value?.reload({ page: 1, where: cFactoryWhere });
};

/*  重置 */
const cFactoryReset = () => {
  cFactoryResetFields();
  cFactoryReload();
};

/* 删除单个 */
const cFactoryRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeCustomerFactory(record.id).then((msg) => {
    hide();
    message.success(msg);
    cFactoryReload();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const cFactoryCurrent = ref(null);

// 弹窗是否打开
const cFactoryVisible = ref(false);

// 弹窗是否打开
const customerExportVisible = ref(false);

// 是否是修改
const cFactoryIsUpdate = ref(false);

// 提交状态
const cFactoryLoading = ref(false);

//
const cFactoryFormRef = ref(null);

// 表单数据
const { form: cFactoryForm, resetFields: cFactoryResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
  customerId: 0,
  longitude: 0,
  latitude: 0,
  radius: 1000,
  fstate2: false,
});


/* 打开编辑弹窗 */
const openCFactoryEdit = (record) => {
  if (!current.value) {
    message.error('请选择客户');
    return
  }

  cFactoryResetFormFields();
  cFactoryFormRef.value?.clearValidate();
  cFactoryCurrent.value = record;
  cFactoryVisible.value = true;
  Object.assign(cFactoryForm, record ?? {});
  if (record == undefined) {
    cFactoryForm.customerId = current.value.id
  } else {
    cFactoryForm.fstate2 = cFactoryForm.fstate == '默认地址' ? true : false
  }
  cFactoryIsUpdate.value = !!record;
};

/* 保存编辑 */
const cFactorySave = () => {
  if (!cFactoryFormRef.value) {
    return;
  }
  cFactoryForm.fstate = cFactoryForm.fstate2 ? '默认地址' : ''
  cFactoryFormRef.value.validate().then(() => {
    cFactoryLoading.value = true;
    const saveOrUpdate = cFactoryIsUpdate.value ? updateCustomerFactory : addCustomerFactory;
    saveOrUpdate(cFactoryForm).then((msg) => {
      cFactoryLoading.value = false;
      message.success(msg);
      cFactoryVisible.value = false;
      cFactoryReload();
    }).catch((e) => {
      cFactoryLoading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
//-----------------工厂地址customer factory-----------------------
</script>

<script>
export default {
  name: 'DemoTest'
};
</script>
<style ></style>

